import { Public } from '@/decorators/public.decorator';
import { SourceMapDTO } from '@/dtos/upload.dto';
import {
  BadRequestException,
  Controller,
  Get,
  Post,
  Req,
} from '@nestjs/common';
import { FastifyFileInterceptor } from 'nest-fastify-multer';
import { diskStorage } from 'fastify-multer';
import { FastifyRequest } from 'fastify';
import { readdir, readFile, rm } from 'fs/promises';
import { clearMap, setMap } from '@/util';

@Controller('upload')
export class UploadController {
  @Get('sourcemap/clear')
  @Public()
  async clearSourceMap() {
    const path = './maps';
    readdir(path).then((files) => {
      for (const file of files) {
        const filePath = `${path}/${file}`;
        rm(filePath);
      }
      clearMap();
    });
    return true;
  }

  @Post('sourcemap')
  @Public()
  @FastifyFileInterceptor('source', {
    storage: diskStorage({
      destination: './maps', // 保存文件的目录
      filename: (req, file, cb) => {
        const fileName = (req.body as SourceMapDTO).fileName;
        if (!fileName) {
          return cb(new BadRequestException('文件名不能为空'));
        }
        return cb(null, fileName);
      },
    }),
  })
  async uploadSourceMap(@Req() req: FastifyRequest) {
    const fileName = (req.body as SourceMapDTO).fileName;
    readFile('./maps/' + fileName, {
      encoding: 'utf-8',
    }).then((source) => {
      setMap(fileName, source);
    });
    return true;
  }
}
